import { useRequest } from 'ahooks';
import { FC, useState } from 'react';
import { useParams } from 'react-router-dom';
import { getQuestionStatListService } from '../../../../../services/stat';
import { Typography, Spin, Table, Pagination } from 'antd';
import useGetComponentInfo from '../../../../../hooks/useGetComponentInfo';
export type PropsType = {
  selectedComponentId: string;
  setSelectedComponentId: (id: string) => void;
  setSelectedComponentType: (type: string) => void;
};
const { Title } = Typography;
const PageStat: FC<PropsType> = (props: PropsType) => {
  const { selectedComponentId, setSelectedComponentId, setSelectedComponentType } = props;
  const { id = '' } = useParams();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [list, setList] = useState([]);
  const { componentList } = useGetComponentInfo();
  const { loading } = useRequest(
    async () => {
      const res = await getQuestionStatListService(id, { page, pageSize });
      return res;
    },
    {
      refreshDeps: [id, page, pageSize],
      onSuccess: (res) => {
        const { total, list = [] } = res;
        setTotal(total);
        setList(list);
      },
    },
  );
  const TableElement = () => {
    const columns = componentList.map((component) => {
      const { props, title, fe_id, type } = component;
      const newTitle = props.title || title;
      return {
        title: (
          <div
            style={{ cursor: 'pointer' }}
            onClick={() => {
              setSelectedComponentId(fe_id);
              setSelectedComponentType(type);
            }}
          >
            <span style={{ color: selectedComponentId === fe_id ? '#1890ff' : 'inherit' }}>
              {newTitle}
            </span>
          </div>
        ),
        dataIndex: component.fe_id,
      };
    });

    return (
      <>
        <Table
          columns={columns}
          dataSource={list}
          rowKey={(item: any) => item._id}
          pagination={false}
        />
        <div style={{ textAlign: 'center', marginTop: '18px' }}>
          <Pagination
            pageSize={pageSize}
            current={page}
            total={total}
            onChange={(page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
            }}
            onShowSizeChange={(current, pageSize) => {
              setPage(current);
              setPageSize(pageSize);
            }}
          />
        </div>
      </>
    );
  };

  return (
    <div>
      <Title level={5}>答卷数量: {!loading && total}</Title>
      {loading && (
        <div style={{ textAlign: 'center', marginTop: '60px' }}>
          <Spin />
        </div>
      )}
      {!loading && <TableElement />}
    </div>
  );
};
export default PageStat;
